#pragma once

#include "Protocol.h"

class Serial;

class Protocol_CT : public Protocol
{
public:
	Protocol_CT();
	~Protocol_CT();

	void init(const std::string& com_device);

	void update();

	Data get_data() const;
	float get_update_frequency() const;


	uint32_t get_packet_loss() const;

private:
	Data data;

	uint32_t m_packet_loss;
	uint32_t m_packet_count;

	typedef std::chrono::high_resolution_clock Clock;
	Clock::time_point m_last_time;

	std::mutex m_buffer_mutex;
	std::vector<uint8_t> m_buffer;

	//one skfry frame (usually 11 bytes)
	std::vector<uint8_t> m_packet;

	void parse_data();
	size_t find_header_offset(const std::vector<uint8_t>& buffer, size_t offset);

	bool parse_user_packet();
	uint32_t m_user_packet_count;
	Clock::time_point m_user_packet_last_time;

	bool parse_link_packet();
	uint32_t m_link_packet_count;
	Clock::time_point m_link_packet_last_time;

	bool parse_rssi_tx_packet();
	bool parse_rssi_rx_packet();


	void serial_callback(const boost::system::error_code& error, size_t bytes_transferred);
	void read_async();

	Data m_data;

	std::vector<uint16_t> m_all_telemetry_data;

	std::vector<uint8_t> m_telemetry_packet;
	size_t m_telemetry_packet_size;
	void parse_telemetry_packet();

	boost::asio::io_service m_io;
	boost::asio::serial_port m_port;
	std::thread m_io_thread;
	std::array<uint8_t, 8192> m_serial_buffer;
};
